package main

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"log"
	"time"
)

type User struct {
	ID  uint `gorm:"primary_key"`//primary_key:设置主键
	Age int             // 列名为 `age`
	Name string         // 列名为 `name`
	Birthday time.Time  // 列名为 `birthday`
	CreatedAt time.Time // 列名为 `created_at`
}
func main() {
	db, err := gorm.Open("mysql", "root:360che.com@tcp(192.168.2.8:3306)/node?charset=utf8&parseTime=True")
	if err != nil {
		panic("数据库连接失败")
	}
	defer db.Close()
	// 全局禁用表名复数
	//db.SingularTable(true)
	//启用sql记录
	db.LogMode(true)
	//创建记录
	//creat(db)
	//检查主键
	//checkP(db)
	//查询
	//selectQuery(db)
	//修改
	//update(db)
	//删除
	delete(db)
	//执行原生SQL
	//raw(db)
}
func creat(db *gorm.DB)  {
	user := User{Name: fmt.Sprintf("aaa%d",time.Now().Unix()),Age: 18, Birthday: time.Now()}
	log.Printf("%+v",user)
	log.Println(db.NewRecord(user))// => 创建`user`前返回`true`(根据主键判断可以创建)
	log.Println(db.NewRecord(user))
	db.Create(&user)
	log.Printf("%+v",user) // => 查看创建结果
	log.Println(db.NewRecord(user))
}
func checkP(db *gorm.DB)  {
	u2 := User{ID:22,Name: "aaaacccc", Age: 18, Birthday: time.Now()}
	log.Println(u2)
	log.Println(db.NewRecord(u2))//根据主键判断不能创建
}
func selectQuery(db *gorm.DB)  {
	user := []User{}
	// 获取第一条记录，按主键排序
	//db.First(&user)
	//// SELECT * FROM user ORDER BY id LIMIT 1;

	// 获取最后一条记录，按主键排序
	//db.Last(&user)
	//// SELECT * FROM user ORDER BY id DESC LIMIT 1;

	// 获取所有记录
	//db.Find(&user)
	//// SELECT * FROM user;

	// 使用主键获取记录
	//db.First(&user, 25)
	//// SELECT * FROM user WHERE id = 10;

	// where条件
	//db.Where("id = ? and age=?", "22",333).First(&user)
	//where条件
	// 获取第一个匹配记录
	//db.Where("name = ?", "aaa1597638303").First(&user)
	//// SELECT * FROM users WHERE name = 'jinzhu' limit 1;
	// 获取所有匹配记录
	//db.Where("age = ?", "12").Find(&user)
	////// SELECT * FROM users WHERE name = 'jinzhu';
	//db.Where("age <> ?", "18").Find(&user)
	//// IN
	//db.Where("name in (?)", []string{"aaa1597638303", "aaa1598497178"}).Find(&user)
	//// LIKE
	//db.Where("name LIKE ?", "%aaa%").Find(&user)
	//// AND
	//db.Where("name = ? AND age >= ?", "aaa1598497178", "11").Find(&user)
	db.Where("name = ?",  "22").Where("age = ?",11).Find(&user)
	//// Time
	//db.Where("updated_at > ?", "2020-08-17").Find(&user)
	//db.Where("created_at BETWEEN ? AND ?", "2020-08-17", "2020-08-30").Find(&user)

	log.Printf("%+v",user)
}
// 执行原生SQL
func raw(db *gorm.DB)  {
	user := []User{}
	//这里有个坑，就是无返回sql使用exec，有返回用raw
	db.Raw("SELECT * FROM user WHERE id = ?;", 22).Scan(&user)
	log.Println(user)
}
func update(db *gorm.DB)  {
	var user User
	db.Model(&user).Where("id = ?", 22).Update("name", "我修改了2")
	log.Println(user)
	db.Where("id = ?", "22").First(&user)
	log.Println(user)
}
func delete(db *gorm.DB)  {
	re := db.Where("id = ?", "23").Delete(User{})
	log.Println(re)
}